﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using DataStorage;

namespace Booky.WinFormsClient
{
    public partial class AddEditBookmark : Form
    {
        AsyncFunc<string, string> addEditBookmarkTask;

        public Bookmark ExistingBookmark { get; set; }

        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
        (
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
        );

    //    In Constructor of the form you need to call this after InitializeComponent()

      //  Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 15, 15));

        public AddEditBookmark()
        {
            InitializeComponent();
            addEditBookmarkTask = new AsyncFunc<string,string>(AddEditBookmarkTask);
            addEditBookmarkTask.Completed += new AsyncFuncCompletedEventHandler<string>(addEditBookmarkTask_Completed);
            //getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;
            //this.FormBorderStyle = 
            Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 0, 0));
        }

        public void DataBind()
        {
            if (this.ExistingBookmark != null)
            {
                txtTitle.Text = this.ExistingBookmark.Name;
                txtLocation.Text = this.ExistingBookmark.Url;
                txtDescription.Text = this.ExistingBookmark.Description;
                this.Text = string.Format(this.Text, "Edit");
            }
            else
            {
                this.Text = string.Format(this.Text, "Add");
            }
        }

        void addEditBookmarkTask_Completed(object sender, AsyncFuncCompletedEventArgs<string> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
            //    textBox1.Text = e.Result;
                //close the window
                this.Close();
                
                //we should be inserting a row to the list control here rather than updating the entire listcontrol
            }

            //progressBar1.Value = 0;
        }

        public MainForm OwnerForm
        {
            get
            {
                return (MainForm)this.Owner;
            }
        }

        private string AddEditBookmarkTask(string question, Func<bool> isCancelled, Action<int> reportProgress)
        {
            Repository r = new Repository();

            if(ExistingBookmark == null)
            {
                Bookmark b = new Bookmark();
                b.Name = txtTitle.Text ?? "";
                b.Description = txtDescription.Text ?? "";
                b.CreatedDate = DateTime.Now;
                b.Url = txtLocation.Text ?? "";

                //Update the bookmark list control with our updated
                OwnerForm.InsertBookmarkToListControl(b);
                r.InsertBookmarkLocalCloud(txtTitle.Text ?? "", txtLocation.Text ?? "", txtDescription.Text ?? "");//UpdateBookmark(txtTitle.Text ?? "", txtLocation.Text ?? "");
            }
            else
            {
                Bookmark newBookmark = new Bookmark();
                newBookmark.Id = ExistingBookmark.Id;
                newBookmark.Name = txtTitle.Text;
                newBookmark.Url = txtLocation.Text;
                newBookmark.Description = txtDescription.Text;
                newBookmark.LastUpdated = DateTime.Now;

                r.UpdateBookmarkLocalCloud(newBookmark);
            }
            
            return "42";
        }

        private void AddEditBookmarkButton_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(errorProvider1.GetError(txtTitle)) && string.IsNullOrEmpty(errorProvider2.GetError(txtTitle)) )
                addEditBookmarkTask.TryInvokeAsync("What is the Answer to the Ultimate Question of Life, the Universe and Everything");
        }

        private void txtTitle_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                this.errorProvider1.SetError(txtTitle, "Title is required");
            }
            else
            {
                errorProvider1.SetError(txtTitle, "");
            }
        }

        private void txtLocation_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtLocation.Text))
            {
                this.errorProvider2.SetError(txtLocation, "Location is required");
            }
            else
            {
                errorProvider2.SetError(txtLocation, "");
            }
        }
    }
}
